package com.eliansun.crawler.downloader.phantomjsdriver;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  用于管理创建phantomjs driver的线程池
 *  @author xpq
 */
public class WebDriverPool {

    private static final int MAX_SZIE =10;

    private static final int RUN_STATUS = 1;

    private AtomicInteger at = new AtomicInteger(RUN_STATUS);

    private List<WebDriver> driverList = Collections.synchronizedList(new ArrayList<WebDriver>());

    private BlockingDeque<WebDriver> webDriverQueue = new LinkedBlockingDeque<WebDriver>();

    public WebDriver getWebDriver() throws InterruptedException {
        WebDriver poll = webDriverQueue.poll();
        if (poll != null){
            return poll;
        }
        if(driverList.size() < MAX_SZIE){
            synchronized (driverList){
                if (driverList.size() < MAX_SZIE){
                    WebDriver webDriver = new PhantomJSDriver();

                    webDriverQueue.add(webDriver);
                    driverList.add(webDriver);
                }
            }
        }
        return webDriverQueue.take();
    }

    public WebDriverPool(){
        System.setProperty("phantomjs.binary.path", "/work/ljh/work/phantomjs-2.1.1-linux-x86_64/bin/phantomjs");
    }

    protected void checkRunning() {
        if (!at.compareAndSet(RUN_STATUS, RUN_STATUS)) {
            throw new IllegalStateException("运行中....");
        }
    }

    public void removeDriver(Object o) {
        driverList.remove(o);
    }

    public void closeAll() {
        boolean b = at.compareAndSet(1, 2);
        if (!b) {
            throw new IllegalStateException("已经关闭....");
        }
        for (WebDriver webDriver : driverList) {
            webDriver.quit();
            webDriver = null;
        }
    }


    public void returnToPool(WebDriver webDriver) {
        checkRunning();
        webDriverQueue.add(webDriver);
    }
}
